package com.ljx.itbbs.server.article.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ljx.itbbs.common.domain.model.LoginUser;
import com.ljx.itbbs.common.domain.vo.resp.PageResp;
import com.ljx.itbbs.common.utils.AssertUtil;
import com.ljx.itbbs.server.article.dao.ArticleDraftDao;
import com.ljx.itbbs.server.article.domain.entity.ArticleDraftEntity;
import com.ljx.itbbs.server.article.domain.entity.ArticleEntity;
import com.ljx.itbbs.server.article.domain.vo.req.ArticleListReq;
import com.ljx.itbbs.server.article.domain.vo.req.ArticleUpdateReq;
import com.ljx.itbbs.server.article.domain.vo.resp.ArticleInfoResp;
import com.ljx.itbbs.server.article.service.ArticleDraftService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ArticleDraftServiceImpl implements ArticleDraftService {

    @Autowired
    private ArticleDraftDao articleDraftDao;

    @Override
    public void saveArticleDraft(ArticleDraftEntity articleDraftEntity) {
        articleDraftDao.save(articleDraftEntity);
    }

    @Override
    public ArticleDraftEntity getArticleDraft(Long articleId) {
        return articleDraftDao.getById(articleId);
    }

    @Override
    public PageResp<ArticleInfoResp> getArticleDraftList(LoginUser loginUser, ArticleListReq articleListReq) {
        IPage<ArticleDraftEntity> iPageList = articleDraftDao.getArticleList(articleListReq, loginUser.getUserId());
        return PageResp.<ArticleInfoResp>builder()
                .list(BeanUtil.copyToList(iPageList.getRecords(), ArticleInfoResp.class))
                .total(iPageList.getTotal())
                .build();
    }

    @Override
    public void updateDraft(Long userId, ArticleUpdateReq req) {
        // 检查权限
        ArticleDraftEntity articleDraft = articleDraftDao.getById(req.getArticleId());
        AssertUtil.isTrue(articleDraft.getUid().equals(userId), "无权限");
        // 更新
        BeanUtils.copyProperties(req, articleDraft);
        articleDraftDao.updateById(articleDraft);
    }

    @Override
    public void deleteDraftArticle(Long userId, Long articleId) {
        articleDraftDao.remove(new LambdaQueryWrapper<ArticleDraftEntity>()
                .eq(ArticleDraftEntity::getUid, userId)
                .eq(ArticleDraftEntity::getId, articleId));
    }
}
